﻿using log4net;
using Rainbow.core;
using Rainbow.utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Rainbow.model
{
    public class GlobalSetting
    {
        private static ILog logger = LogManager.GetLogger(typeof(GlobalSetting));

        /// <summary>
        /// 远程服务器根路径
        /// </summary>
        public string rootPath;

        /// <summary>
        /// 下线线程数
        /// </summary>
        public int downloadThreadNum;
        /// <summary>
        /// 上传线程数
        /// </summary>
        internal int uploadThreadNum;

        public GlobalSetting()
        {
            Reset();
        }

        public GlobalSetting(GlobalSetting setting) : this()
        {
            Copy(setting);
        }

        public void Reset()
        {
            rootPath = "/";
            downloadThreadNum = 5;
            uploadThreadNum = 5;
        }

        public void Copy(GlobalSetting setting)
        {
            this.rootPath = setting.rootPath;
            this.downloadThreadNum = setting.downloadThreadNum;
            this.uploadThreadNum = setting.uploadThreadNum;
        }

        public GlobalSetting Clone()
        {
            return new GlobalSetting(this);
        }

        public int Load()
        {
            int rn = 0;

            string dataFile = TW_App.fileManager.globalSettingFile;
            bool existsFlag = File.Exists(dataFile);
            if(!existsFlag)
            {
                Reset();
                logger.WarnFormat("全局设置文件[{0}]不存在",dataFile);
                return -2;
            }

            GlobalSetting setting = XmlUtil.Load<GlobalSetting>(dataFile);
            if (setting != null)
            {
                Copy(setting);
                rn = 0;
            }
            else
            {
                Reset();
                logger.ErrorFormat("加载全局设备[{0}]失败", dataFile);
                rn = -3;
            }

            return rn;
        }

        public bool Save()
        {
            string dataFile = TW_App.fileManager.globalSettingFile;

            GlobalSetting globalSetting = new GlobalSetting(this);
            bool rn = XmlUtil.Save<GlobalSetting>(dataFile, globalSetting);
            return rn;
        }
    }
}
